package com.example.communist_app_api.controller.uniapp;


import com.example.communist_app_api.service.LikeService;
import com.example.communist_app_api.service.UserService;
import com.example.communist_app_api.util.JwtUtils;
import com.example.communist_app_api.util.R;
import com.example.communist_app_api.vo.uniapp.req.LikeReq;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/uniApp/like/")
@Api("点赞controller控制器")
public class UniAppLikeController {

    @Autowired
    private LikeService likeService;

    @Autowired
    private UserService userService;


    @PostMapping("/insertArticleLike")
    @ApiOperation("添加文章点赞")
    public R insertArticleLike(@RequestBody LikeReq likeReq,HttpServletRequest httpServletRequest)
    {
        Integer userId = getUserIdByWeb(httpServletRequest);
        int insertArticleLikeNum = likeService.insertLike(userId,likeReq.getArticleId());

        if (insertArticleLikeNum == 1)
        {
            return R.ok();
        }

        else return R.error();
    }

    @PostMapping("/deleteArticleLike")
    @ApiOperation("取消文章点赞")
    public R deleteArticleLike(@RequestBody LikeReq likeReq,HttpServletRequest httpServletRequest)
    {
        Integer userId = getUserIdByWeb(httpServletRequest);
        int deleteNum = likeService.deleteLike(userId,likeReq.getArticleId());

        if (deleteNum == 1)
        {
            return R.ok();
        }
        else
            return R.error();
    }

    private Integer getUserIdByWeb(HttpServletRequest httpServletRequest){
        String token = httpServletRequest.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        String id = claims.getSubject();
        int userId = Integer.parseInt(id);
        return userId;
    }

}
